/**
 * 
 */
package service;

import java.text.SimpleDateFormat;
import java.util.Date;

import utils.Page;
import dao.SecurityDao;
import dao.SecurityDaoImpl;
import dao.UserDao;
import dao.UserDaoImpl;
import exception.ApplicationException;
import model.Administrator;
import model.Door;
import model.Log;
import model.Message;
import model.User;

/**
 * @ClassName: UserServiceImpl
 * @Description:
 * @author Hongming Wu
 * @date 2013-12-6
 * 
 */
public class UserServiceImpl implements UserService {

	@Override
	public User getUserByID(String userID) {
		User user = null;

		try {
			UserDao ud = new UserDaoImpl();
			user = ud.getUserByID(userID);
		} catch (Exception e) {
			throw new ApplicationException("error!", e);
		}
		return user;
	}

	@Override
	public void updateUser(User user) {
		try {
			UserDao ud = new UserDaoImpl();
			ud.updateUser(user);
		} catch (Exception e) {
			throw new ApplicationException("error!", e);
		}

	}

	@Override
	public Page loadPagedLogs(Page page, UserQueryHelper helper, User user) {
		try {
			UserDao ud = new UserDaoImpl();
			page.setTotalRecNum(ud.countMylogs(helper, user));
			page.setPageContent(ud.getScopedLogs(helper, user,
					page.getStartIndex(), page.getEndIndex()));
		} catch (Exception e) {
			throw new ApplicationException("error!", e);
		}
		return page;
	}

	@Override
	public void createMsg(User user, Message msg) {

		UserDao ud = new UserDaoImpl();
		ud.createMsg(user, msg);

	}

	@Override
	public void openDoor(Door door, User user) {
		try {
			Door d = new Door();
			User u = new User();
			Log l = new Log();

			UserDao ud = new UserDaoImpl();
			SecurityDao sd = new SecurityDaoImpl();
			d = sd.getDoorByID(door.getDoor_ID());
			u = ud.getUserByID(user.getUser_ID());
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date a = new Date();
			String str = df.format(a);
			l.setLog_Date(str);
			l.setOperator(u.getUser_ID());

			if (u.getAccess_ID() >= d.getArea_ID()) {
				ud.openDoor(door);
				System.out
						.println(u.getUser_ID() + " Access : "
								+ u.getAccess_ID() + " " + d.getDoor_ID()
								+ " ----Pass");
				l.setLog_Content(u.getUser_ID() + " Access : "
						+ u.getAccess_ID() + " " + d.getDoor_ID() + " ----Pass");
				sd.createLog(l, door);
			} else {
				l.setLog_Content(u.getUser_ID() + " Access : "
						+ u.getAccess_ID() + " " + d.getDoor_ID()
						+ " ----Decline");
				System.out.println(user.getUser_ID() + " Access : "
						+ user.getAccess_ID() + " " + d.getDoor_ID()
						+ " ----Decline");
				sd.createLog(l, door);
			}

		} catch (Exception e) {
			throw new ApplicationException("error!", e);
		}

	}

}
